package zjitc.service;

import zjitc.dao.UserDao;
import zjitc.dao.UserDaoImpl;
import zjitc.domain.PageBean;
import zjitc.domain.User;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService{

    private UserDao dao = new UserDaoImpl();
    @Override
    public List<User> findAll() {
        return dao.findAll();
    }

    @Override
    public User login(User user) {
        return dao.login(user);
    }

    @Override
    public void addUser(User user) {
        dao.addUser(user);
    }
    @Override
    public void deleteUser(String id) {
        dao.deleteUser(id);
    }
    @Override
    public User findUserById(int id) {
        return dao.findUserById(id);
    }
    @Override
    public void updateUser(User user) {
        dao.updateUser(user);
    }
    @Override
    public void delSelected(String[] uids) {
        for (String uid : uids) {
            dao.deleteUser(uid);
        }
    }
    /**
     * 分页查询
     *
     * @param _currentPage
     * @param _rows
     * @param condition
     * @return
     */
    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
        int currentPage = Integer.parseInt(_currentPage);
        if(currentPage<1){
            currentPage=1;
        }
        if(currentPage>5){
            currentPage=5;
        }
        int rows = Integer.parseInt(_rows);

        //1. 创建空的PageBean对象
        PageBean<User> pb = new PageBean<>();
        //2. 设置参数
        pb.setCurrentPage(currentPage);
        pb.setRows(rows);
        //3. 调用dao查询总记录数
        int totalCount = dao.findTotalCount(condition);
        pb.setTotalCount(totalCount);
        //4. 调用dao查询list集合
        //计算开始的记录索引
        int start = (currentPage-1)*rows;
        List<User> list = dao.findByPage(start,rows,condition);
        pb.setList(list);
        //5. 计算总页码
        int totalPage = (totalCount%rows)==0?totalCount/rows:totalCount/rows+1;
        pb.setTotalPage(totalPage);
        return pb;
    }
}
